package com.simpletour.qa.common.base;

import com.simpletour.qa.common.http.ObjectRestResponse;
import com.simpletour.qa.common.http.ResponseCode;
import com.simpletour.qa.common.http.ResponseMsg;
import com.simpletour.qa.common.util.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 *
 * @author zhaohw
 * @date 2018-06-20 11:28
 */

public class BaseController<Biz extends BaseBiz,Entity,ID>{

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected Biz baseBiz;

    @RequestMapping(value = "",method = RequestMethod.POST)
    public ObjectRestResponse add(@RequestBody @Valid Entity entity, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            List<FieldError> errorList = bindingResult.getFieldErrors();
            return ObjectRestResponse.builder()
                    .code(ResponseCode.PARAM_CHECK_ERROR)
                    .build();
        }
        //todo 新增失败校验
        baseBiz.save(entity);
        return ObjectRestResponse.builder()
                .code(ResponseCode.SUCCESS)
                .msg(ResponseMsg.SUCCESS)
                .build();
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ObjectRestResponse get(@PathVariable ID id){
        Entity object= (Entity) baseBiz.findById(id).orElse(null);
        return ObjectRestResponse.builder()
                .code(ResponseCode.SUCCESS)
                .result(object)
                .msg(ResponseMsg.SUCCESS)
                .build();
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public ObjectRestResponse update(@PathVariable ID id, @RequestBody Entity entity){
        try {
            ReflectionUtils.setPrimaryKey(entity,id);
            baseBiz.save(entity);
        }catch (DataIntegrityViolationException e){
            return ObjectRestResponse.builder()
                    .code(ResponseCode.USER_NAME_DUPLICATE)
                    .msg(ResponseMsg.USER_NAME_DUPLICATE)
                    .build();
        }catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
            return ObjectRestResponse.builder()
                    .code(ResponseCode.SERVER_INTERNAL_ERROR)
                    .msg(ResponseMsg.SERVER_INTERNAL_ERROR)
                    .build();
        }
        return ObjectRestResponse.builder()
                .code(ResponseCode.SUCCESS)
                .msg(ResponseMsg.SUCCESS)
                .build();
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public ObjectRestResponse remove(@PathVariable ID id){
        baseBiz.deleteById(id);
        return ObjectRestResponse.builder()
                .code(ResponseCode.SUCCESS)
                .msg(ResponseMsg.SUCCESS)
                .build();
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
    public ObjectRestResponse all(){
        List<Entity> all = baseBiz.findAll();
        return ObjectRestResponse.builder()
                .code(ResponseCode.SUCCESS)
                .result(all)
                .msg(ResponseMsg.SUCCESS)
                .build();
    }

    /**
     * 获取当前请求的用户id
     * 此header通过网关解析JWT时所添加
     * @return 用户id
     */
    protected Integer getCurrentUserId(){
        String userId = request.getHeader("userId");
        return Integer.parseInt(userId);
    }
}
